package com.fxkj.cloud.drms.infra.sql.TDengine;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class  TDEngineResultSetFuture<T> implements ListenableFuture<TDEngineResultSet<T>> {

    private final SettableFuture<TDEngineResultSet<T>> mainFuture;


    public TDEngineResultSetFuture(SettableFuture<TDEngineResultSet<T>> mainFuture) {
        this.mainFuture = mainFuture;
    }

    public TDEngineResultSet<T> getUninterruptibly() {
        return getSafe();
    }

    public TDEngineResultSet<T> getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
        return getSafe(timeout, unit);
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return mainFuture.cancel(mayInterruptIfRunning);
    }

    @Override
    public boolean isCancelled() {
        return mainFuture.isCancelled();
    }

    @Override
    public boolean isDone() {
        return mainFuture.isDone();
    }

    @Override
    public TDEngineResultSet get() throws InterruptedException, ExecutionException {
        return mainFuture.get();
    }

    @Override
    public TDEngineResultSet get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return mainFuture.get(timeout, unit);
    }

    @Override
    public void addListener(Runnable listener, Executor executor) {
        mainFuture.addListener(listener, executor);
    }

    private TDEngineResultSet getSafe() {
        try {
            return mainFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }

    private TDEngineResultSet getSafe(long timeout, TimeUnit unit) throws TimeoutException {
        try {
            return mainFuture.get(timeout, unit);
        } catch (InterruptedException | ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }
}
